#!/usr/bin/ruby
require 'rubygems'
require 'mechanize'
require 'date'
require 'net/smtp'
require 'base64'

class Send_mail
	def send(from, from_alias, to, to_alias, subject, message)
		msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias}
Subject: #{subject}
Date: #{Time.now}

#{message}
END_OF_MESSAGE

		Net::SMTP.start('mail.fake.cn', 25 ) do |smtp|
			smtp.send_message msg, from, to
			smtp.finish
		end
	end
end

def send_msg(content)
	from = "AutoWaMei@XiaoNei.com"
	from_alias = "AutoWaMei"
	to = ["fake@fake.cn"]
	to_alias = "liubin <fake@fake.cn>"
	subject = "Auto WaMei Report"

	send_mail = Send_mail.new
	send_mail.send(from, from_alias, to, to_alias, subject, content)
end

username = Base64.decode64("emp1bGl1Ymlu")
password = Base64.decode64("mypass_base64")

begin
	$agent = WWW::Mechanize.new
	$agent.user_agent_alias = "Windows IE 6"
	puts "[程序]: <#{Time.now()}> 正在登录校內..."
	page = $agent.get("http://www.xiaonei.com")
	search_form = page.forms.first
	search_form.fields.name("email").value = username
	search_form.fields.name("password").value = password
	page = $agent.submit(search_form)
	$userid = page.parser.search("//div[@class='menu-title']/a")[0]["href"].match(/\?id=(\d*)/)[1]
	puts $userid

	# parse friends list
	uids = Array.new
	page = $agent.get("http://friendsell.xiaonei.com/friendsell/suggest.do")
	uids_tmp = page.parser().to_s.split(/"head_url"/)
	uids_tmp.each do |str|
		m = str.match(/"uid":(\d*),/)
		uids << m[1].to_s if m != nil
	end

	# parse tsc, ak, ...
	postdata = {}
	page = $agent.get("http://xiaonei.com/profile.do?id=#{$userid}")
	submit =  page.parser.search("//form[@id='commentPostForm']/div[@class='submit']")
	postdata[:tsc] = submit.search("//input[@name='tsc']")[0]["value"]
	postdata[:ak] = submit.search("//input[@name='ak']")[0]["value"]
	postdata[:profilever] = submit.search("//input[@name='profilever']")[0]["value"]
	postdata[:from] = "main"
	postdata[:id] = $userid
	postdata[:body] = "哎呀，不好意思哈，都要元旦了，才祝大家圣诞快乐！\n迟到了一点点，大家不要挑剔哈。"

	uids.each do |cc|
		puts $agent.post("http://xiaonei.com/gossip.do", postdata )
		postdata[:cc] = cc
		puts postdata.to_s
	end

rescue Exception => e
	puts "#{e}\n"
end
